package com.gl.emms.whale.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.security.auth.PrivateCredentialPermission;
import cn.com.pangutec.ganlinux.firsttips.firsttipsview.GlobalAttr;
import cn.com.pangutec.ganlinux.firsttips.firsttipsview.TipsAttr;
import cn.com.pangutec.ganlinux.firsttips.firsttipsview.TipsImageView;
import cn.com.pangutec.ganlinux.firsttips.firsttipsview.TipsImageView.OnSkipActionListener;
import cn.com.pangutec.ganlinux.firsttips.firsttipsview.TipsImageView.OnTipsClickActionListener;
import com.gl.emms.client.android.EMMSPushManager;
import com.gl.emms.nio.mutual.ReplyBody;
import com.gl.emms.nio.mutual.ServerMessage;
import com.gl.emms.whale.R;
import com.gl.emms.whale.adapter.GroupAdapter;
import com.gl.emms.whale.adapter.MyExAdapter;
import com.gl.emms.whale.adapter.MyInfoViewAdapter;
import com.gl.emms.whale.adapter.MyPagerAdapter;
import com.gl.emms.whale.adapter.SystenMsgViewAdapter;
import com.gl.emms.whale.app.MyApplication;
import com.gl.emms.whale.app.WhaleMonitorActivity;
import com.gl.emms.whale.bean.User;
import com.gl.emms.whale.db.MessageDB;
import com.gl.emms.whale.tranbean.TranObject;
import com.gl.emms.whale.util.GroupEntity;
import com.gl.emms.whale.util.GroupFriend;
import com.gl.emms.whale.util.MyInfoEntity;
import com.gl.emms.whale.util.RoomViewEntity;
import com.gl.emms.whale.util.SharePreferenceUtil;
import com.gl.emms.whale.util.SystemMsgEntity;
import com.readystatesoftware.viewbadger.BadgeView;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
/**
 * 好友列表的Activity
 * 
 * @author ganlinux
 * 
 */
public class TabActivity extends WhaleMonitorActivity implements OnClickListener {

	Timer recv_timer;//接收定时器

	private long mExitTime = System.currentTimeMillis();
	private Dialog noticeDialog;
	private static final int PAGE1 = 0;// 页面1
	private static final int PAGE2 = 1;// 页面2
	private static final int PAGE3 = 2;// 页面3
	private static final int PAGE4 = 3;// 页面4

	//系统消息
	SystenMsgViewAdapter systemMsgViewAdapter = null;
	private List<SystemMsgEntity> systemMsgList = null;
	private BadgeView systemMsgbadgeView;
	private TextView systemMessgeText;// 文字


	private MyExAdapter myExAdapter;// 好
	//private LinearLayout mRecentLayout;// 最近会话的listView
	private RoomOverviewListView mListView_RoomOverview;
	private List<User> list_data;
	private List<GroupFriend> group;// 需要传递给适配器的数据
	private String[] groupName = { "能量信息", "电量信息", "水量信息" };// 大组成员名
	private int []roomview_imgs = {R.drawable.roomview_ye,R.drawable.roomview_bjsz,R.drawable.roomview_fmzt,R.drawable.roomview_zje,R.drawable.roomview_jswd,R.drawable.roomview_hswd,R.drawable.roomview_ls,R.drawable.analysis_power,R.drawable.analysis_water};
	private int newNum = 0;
	private BadgeView yuebadgeView;
	private RoomViewEntity roomViewEntity;


	private ListView mListView_systemMsg;
	private ListView mListView_EnergyAnalysis;// 群组listView
	private ListView mListView_MyInfo;// 群组listView

	private ViewPager mPager;
	private List<View> mListViews;// Tab页面



	private LinearLayout layout_body_activity;
	private LinearLayout img_recent_chat;// 最近会话
	private LinearLayout img_friend_list;// 好友列表
	private LinearLayout img_group_friend;// 群组
	private LinearLayout img_myinfo;
	private ImageView myHeadImage;// 头像

	//private TextView myName;// 名字

	private ImageView cursor;// 标题背景图片

	private int currentIndex = PAGE1; // 默认选中第2个，可以动态的改变此参数值
	private int offset = 0;// 动画图片偏移量
	private int bmpW;// 动画图片宽度

	private TranObject msg;

	private MenuInflater mi;// 菜单

	private ExitView mExitView;//
	/*
	private int[] imgs = { R.drawable.icon, R.drawable.f1, R.drawable.f2,
			R.drawable.f3, R.drawable.f4, R.drawable.f5, R.drawable.f6,
			R.drawable.f7, R.drawable.f8, R.drawable.f9 };// 头像资源
	 */
	//private MyApplication application;
	private int[] myinfostr = { R.string.myinfo1str, R.string.myinfo2str, R.string.myinfo3str,
			R.string.myinfo4str, R.string.myinfo5str, R.string.myinfo6str, R.string.myinfo7str,R.string.myinfo8str};
	private int[] myinfoimg = { R.drawable.myinfo_account, R.drawable.roomview_fmzt, R.drawable.myinfo_autocontrol,
			R.drawable.myinfo_settings, R.drawable.myinfo_reportrepair, R.drawable.myinfo_recharge, R.drawable.list_group,R.drawable.myinfo_changepwd};

	private TipsImageView tipsImageView = null;//tips控件

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyApplication.getInstance().addActivity(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.activity_tab);
		//application = (MyApplication) this.getApplicationContext();
		initData();// 初始化数据
		initSystemMsg();
		initImageView();// 初始化动画
		initViews();// 初始化界面
	}

	@Override
	protected void onResume() {// 如果从后台恢复，服务被系统干掉，就重启一下服务
		// TODO Auto-generated method stub
		/*
		newNum = application.getRecentNum();// 从新获取一下全局变量
		if (!application.isClientStart()) {
			Intent service = new Intent(this, GetMsgService.class);
			startService(service);
		}
		new SharePreferenceUtil(this, Constants.SAVE_USER).setIsStart(false);
		NotificationManager manager = application.getmNotificationManager();
		if (manager != null) {
			manager.cancel(Constants.NOTIFY_ID);
			application.setNewMsgNum(0);// 把消息数目置0
			application.getmRecentAdapter().notifyDataSetChanged();
		}
		 */
		super.onResume();
	}

	/**
	 * 初始化系统数据
	 */
	private void initData() {
		/*
		userDB = new UserDB(FriendListActivity.this);// 本地用户数据库
		messageDB = new MessageDB(this);// 本地消息数据库
		util = new SharePreferenceUtil(this, Constants.SAVE_USER);

		msg = (TranObject) getIntent().getSerializableExtra(Constants.MSGKEY);// 从intent中取出消息对象
		if (msg == null) {// 如果为空，说明是从后台切换过来的，需要从数据库中读取好友列表信息
			list = userDB.getUser();
		} else {// 如果是登录界面切换过来的，就把好友列表信息保存到数据库
			list = (List<User>) msg.getObject();
			userDB.updateUser(list);
		}
		 */
		Intent intent = getIntent();  
		roomViewEntity = (RoomViewEntity)intent.getSerializableExtra("RoomView");

		list_data = new ArrayList<User>();
		//list_data = getUser();
		//updataRoomView(roomViewEntity);
		for (int i = 0; i < 9; i++) {
			User u = new User();
			u.setId(roomViewEntity.getRooms());

			u.setImg(roomview_imgs[i]);
			u.setIsOnline(1);

			switch (i) {
			case 0:
				u.setName(String.format(getString(R.string.yeStr),roomViewEntity.getYe()));
				u.setGroup(0);
				break;
			case 1:
				u.setName(String.format(getString(R.string.bjszStr),roomViewEntity.getBjsz()));
				u.setGroup(0);
				break;
			case 2:
				String fmzt ;
				if(roomViewEntity.getFmzt().equals("1"))
				{
					fmzt = "开";
				}else if(roomViewEntity.getFmzt().equals("2"))
				{
					fmzt = "关";
				}else
				{
					fmzt = "过渡";
				}
				u.setName(String.format(getString(R.string.fmztStr),fmzt));
				u.setGroup(0);
				break;
			case 3:
				u.setName(String.format(getString(R.string.zjeStr),roomViewEntity.getZje()));
				u.setGroup(0);
				break;
			case 4:
				u.setName(String.format(getString(R.string.jswdStr),roomViewEntity.getJswd()));
				u.setGroup(0);
				break;
			case 5:
				u.setName(String.format(getString(R.string.hswdStr),roomViewEntity.getHswd()));
				u.setGroup(0);
				break;
			case 6:
				u.setName(String.format(getString(R.string.llStr),roomViewEntity.getLs()));
				u.setGroup(0);
				break;
			case 7:
				u.setName(String.format(getString(R.string.dbyeStr),roomViewEntity.getDbye()));
				u.setGroup(1);
				break;
			case 8:
				u.setName(String.format(getString(R.string.sbylStr),roomViewEntity.getSbyl()));
				u.setGroup(2);
				break;
			default:
				break;
			}
			list_data.add(u);
		}
		initListViewData(list_data);
	}
	/**
	 * 初始化系统数据
	 */
	private void initSystemMsg() {

		systemMsgList = new ArrayList<SystemMsgEntity>();
		MessageDB messageDB = new MessageDB(this);
		systemMsgList = messageDB.getMsg();
		setSystemMsgList(systemMsgList);


	}


	/**
	 * 处理服务器传递过来的用户数组数据，
	 * 
	 * @param list
	 *            从服务器获取的用户数组
	 */
	private void initListViewData(List<User> list) {
		group = new ArrayList<GroupFriend>();// 实例化
		for (int i = 0; i < groupName.length; ++i) {// 根据大组的数量，循环给各大组分配成员
			List<User> child = new ArrayList<User>();// 装小组成员的list
			GroupFriend groupInfo = new GroupFriend(groupName[i], child);// 我们自定义的大组成员对象
			for (User u : list) {
				if (u.getGroup() == i)// 判断一下是属于哪个大组
					child.add(u);
			}
			group.add(groupInfo);// 把自定义大组成员对象放入一个list中，传递给适配器
		}
	}
	private void addData(List<User> list) {
		group.clear();
		for (int i = 0; i < groupName.length; ++i) {// 根据大组的数量，循环给各大组分配成员
			List<User> child = new ArrayList<User>();// 装小组成员的list
			GroupFriend groupInfo = new GroupFriend(groupName[i], child);// 我们自定义的大组成员对象
			for (User u : list) {
				if (u.getGroup() == i)// 判断一下是属于哪个大组
					child.add(u);
			}
			group.add(groupInfo);// 把自定义大组成员对象放入一个list中，传递给适配器
		}
	}

	/**
	 * 初始化动画
	 */
	private void initImageView() {
		cursor = (ImageView) findViewById(R.id.tab2_bg);
		bmpW = BitmapFactory.decodeResource(getResources(),
				R.drawable.topbar_toleft).getWidth();// 获取图片宽度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		// System.out.println("屏幕宽度:" + screenW);
		offset = (screenW / 4 - bmpW) / 2;// 计算偏移量:屏幕宽度/3，平分为3分，如果是3个view的话，再减去图片宽度，因为图片居中，所以要得到两变剩下的空隙需要再除以2
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);// 初始化位置
		cursor.setImageMatrix(matrix);// 设置动画初始位置
	}

	public void initViews() {
		mi = new MenuInflater(this);


		layout_body_activity = (LinearLayout) findViewById(R.id.bodylayout);

		img_recent_chat = (LinearLayout) findViewById(R.id.tab1layout);
		img_recent_chat.setOnClickListener(this);



		setImg_friend_list((LinearLayout) findViewById(R.id.tab2layout));
		getImg_friend_list().setOnClickListener(this);

		img_group_friend = (LinearLayout) findViewById(R.id.tab3layout);
		img_group_friend.setOnClickListener(this);

		img_myinfo = (LinearLayout) findViewById(R.id.tab4layout);
		img_myinfo.setOnClickListener(this);

		//myName = (TextView) findViewById(R.id.friend_list_myName);

		cursor = (ImageView) findViewById(R.id.tab2_bg);

		layout_body_activity.setFocusable(true);

		mPager = (ViewPager) findViewById(R.id.viewPager);
		mListViews = new ArrayList<View>();
		LayoutInflater inflater = LayoutInflater.from(this);
		View lay1 = inflater.inflate(R.layout.tab1, null);
		View lay2 = inflater.inflate(R.layout.tab2, null);
		View lay3 = inflater.inflate(R.layout.tab3, null);
		View lay4 = inflater.inflate(R.layout.tab4, null);
		mListViews.add(lay1);
		mListViews.add(lay2);
		mListViews.add(lay3);
		mListViews.add(lay4);
		mPager.setAdapter(new MyPagerAdapter(mListViews));
		mPager.setCurrentItem(PAGE1);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());

		// 下面是最近会话界面处理
		//mRecentLayout = (LinearLayout) lay1.findViewById(R.id.tab1_LelativeLayout1);
		//mRecentAdapter = new RecentChatAdapter(FriendListActivity.this,application.getmRecentList());// 从全局变量中获取最近聊天对象数组
		//mRecentListView.setAdapter(application.getmRecentAdapter());// 先设置空对象，要么从数据库中读出
		//mGroupListView.setAdapter(new RecentChatAdapter()));
		mListView_RoomOverview = (RoomOverviewListView) lay1.findViewById(R.id.tab1_listView2);
		myExAdapter = new MyExAdapter(this, group);
		mListView_RoomOverview.setAdapter(myExAdapter);
		for(int i = 0; i < myExAdapter.getGroupCount(); i++){

			mListView_RoomOverview.expandGroup(i);

		}
		mListView_RoomOverview.setGroupIndicator(null);// 不设置大组指示器图标，因为我们自定义设置了
		//mListView_RoomOverview.setDivider(null);// 设置图片可拉伸的
		mListView_RoomOverview.setFocusable(true);// 聚焦才可以下拉刷新
		mListView_RoomOverview.setonRefreshListener(new MyRefreshListener());
		if (!(roomViewEntity.getState().equals("000001"))) {
			//异常
			mListView_RoomOverview.onDataException();
		}
		/*
		//yuebadgeView = new BadgeView(this, );
		yuebadgeView = new BadgeView(this, (View)myExAdapter.getChild(0,0));
		yuebadgeView.setText("你有新消息");
		yuebadgeView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
        //badge1.setTextColor(Color.RED);
        //badge1.setBadgeBackgroundColor(Color.YELLOW);
		yuebadgeView.setTextSize(12);
		yuebadgeView.toggle();
		 */
		mListView_RoomOverview.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				switch (groupPosition) {
				case 0:
					switch (childPosition) {
					case 0://充值

						Intent recharge = new Intent(TabActivity.this,RechargeActivity.class);  
						startActivity(recharge);
						break;
					case 2://阀门强制控制
						Intent valveControl = new Intent(TabActivity.this,ValveControlActivity.class);  
						startActivity(valveControl);
					default:
						break;
					}
					break;

				default:
					break;
				}
				return true;
			}
		});

		// 下面是处理好友列表界面处理
		mListView_systemMsg = (ListView) lay2.findViewById(R.id.tab2_listView);
		systemMsgViewAdapter = new SystenMsgViewAdapter(this, getSystemMsgList());
		mListView_systemMsg.setAdapter(systemMsgViewAdapter);


		mListView_systemMsg.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Toast.makeText(TabActivity.this, "长按了第"+(position+1)+"条信息", Toast.LENGTH_SHORT).show();
				final int deleteId=position;
				Builder dialogBuidler=new Builder(TabActivity.this);
				dialogBuidler.setMessage("确定删除这条信息么？");
				dialogBuidler.setTitle("消息提示");
				dialogBuidler.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						removeMsg(deleteId);
						//mylist.setAdapter(myAdapter);
						//						myAdapter.notifyDataSetChanged();
						Toast.makeText(TabActivity.this, "删除成功", Toast.LENGTH_LONG).show();

					}
				});

				dialogBuidler.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
				dialogBuidler.create().show();
				return true;
			}
		});
		mListView_systemMsg.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,int position, long id) {
				// TODO Auto-generated method stub

				Intent systemMsg = new Intent(TabActivity.this,SystemMsgActivity.class);  
				// 通过Bundle  
				Bundle bundle = new Bundle(); 
				bundle.putSerializable("systemMsgEntity",systemMsgList.get(position));
				systemMsg.putExtras(bundle);
				startActivity(systemMsg);

			}
		});
		systemMessgeText = (TextView) findViewById(R.id.tab2text);
		systemMsgbadgeView = new BadgeView(this, systemMessgeText);
		updateSystemMsgBadge();

		/*
		myExAdapter = new MyExAdapter(this, group);
		myListView.setAdapter(myExAdapter);
		myListView.setGroupIndicator(null);// 不设置大组指示器图标，因为我们自定义设置了
		myListView.setDivider(null);// 设置图片可拉伸的
		myListView.setFocusable(true);// 聚焦才可以下拉刷新
		myListView.setonRefreshListener(new MyRefreshListener());
		 */

		// 下面是群组界面处理
		mListView_EnergyAnalysis = (ListView) lay3.findViewById(R.id.tab3_listView);

		List<GroupEntity> groupList = new ArrayList<GroupEntity>();
		GroupEntity entity = new GroupEntity(R.drawable.analysis_energy, "能量分析", "节约能源");
		GroupEntity entity2 = new GroupEntity(R.drawable.analysis_power, "电量分析","节约能源");
		GroupEntity entity3 = new GroupEntity(R.drawable.analysis_water, "水量分析","节约能源");
		groupList.add(entity);
		groupList.add(entity2);
		groupList.add(entity3);
		GroupAdapter adapter = new GroupAdapter(this, groupList);
		mListView_EnergyAnalysis.setAdapter(adapter);
		mListView_EnergyAnalysis.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,int position, long id) {
				// TODO Auto-generated method stub
				ConnectivityManager connectMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

				NetworkInfo info = connectMgr.getActiveNetworkInfo();
				final int press_position = position;
				//判断网络是否是wifi。
				//在判断之前一定要进行的非空判断，如果没有任何网络连接info ==null
				if(info.getType() != ConnectivityManager.TYPE_WIFI)
				{
					AlertDialog.Builder builder = new Builder(TabActivity.this);
					builder.setTitle("注意");
					builder.setMessage("此功能会产生很大流量，建议在wifi情况下使用");
					builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {			
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}

					});
					builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {			
						public void onClick(DialogInterface dialog, int which) {
							switch (press_position) {
							case 0:
								Intent intent = new Intent(TabActivity.this,EnergyAnalysisActivity.class);  
								startActivity(intent);
								break;
							case 1:
								Intent intent1 = new Intent(TabActivity.this,EnergyAnalysisActivity.class);  
								startActivity(intent1);
								break;
							case 2:
								Intent intent2 = new Intent(TabActivity.this,EnergyAnalysisActivity.class);  
								startActivity(intent2);
								break;

							default:
								break;
							}
						}
					});

					noticeDialog = builder.create();
					noticeDialog.show();
				}else {
					switch (press_position) {
					case 0:
						Intent intent = new Intent(TabActivity.this,EnergyAnalysisActivity.class);  
						startActivity(intent);
						break;
					case 1:
						Intent intent1 = new Intent(TabActivity.this,EnergyAnalysisActivity.class);  
						startActivity(intent1);
						break;
					case 2:
						Intent intent2 = new Intent(TabActivity.this,EnergyAnalysisActivity.class);  
						startActivity(intent2);
						break;

					default:
						break;
					}
				}
			}
		});



		mListView_MyInfo = (ListView) lay4.findViewById(R.id.tab4_listView);
		List<MyInfoEntity> myInfoList = new ArrayList<MyInfoEntity>();

		int myinfocnt = Integer.parseInt(this.getResources().getString(R.string.myinfocnt));
		for (int i = 0; i < myinfocnt; i++) {
			MyInfoEntity myInfoEntity;
			String myInfoString = this.getResources().getString(myinfostr[i]);
			myInfoEntity= new MyInfoEntity(myinfoimg[i], myInfoString);
			myInfoList.add(myInfoEntity);
		}

		MyInfoViewAdapter myInfoAdapter = new MyInfoViewAdapter(this, myInfoList);
		mListView_MyInfo.setAdapter(myInfoAdapter);
		mListView_MyInfo.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,int position, long id) {
				// TODO Auto-generated method stub
				switch (position) {
				case 0://我的信息
					Intent accountInfo = new Intent(TabActivity.this,AccountInfoActivity.class);  
					startActivity(accountInfo);
					break;
				case 1://阀门强制控制
					Intent valveControl = new Intent(TabActivity.this,ValveControlActivity.class);  
					startActivity(valveControl);
					break;
				case 2://阀门定时控制
					Intent valveAutoControl = new Intent(TabActivity.this,ValveAutoControlActivity.class);  
					startActivity(valveAutoControl);
					break;
				case 3://设置
					Intent setting = new Intent(TabActivity.this,SettingActivity.class);  
					startActivity(setting);
					break;
				case 4://报修设备
					Intent reportRepair = new Intent(TabActivity.this,ReportRepairActivity.class);  
					startActivity(reportRepair);
					break;
				case 5://充值
					//showToask("充值功能未开放！");
					Intent recharge = new Intent(TabActivity.this,RechargeActivity.class);  
					startActivity(recharge);
					break;
				case 6://绑定用户
					showToask("绑定用户功能未开放！");
					//Intent bindAccount = new Intent(TabActivity.this,BindAccountActivity.class);  
					//startActivity(bindAccount);
					break;
				case 7://修改密码
					Intent changePassword = new Intent(TabActivity.this,ChangePasswordActivity.class);  
					startActivity(changePassword);
					break;

				default:
					break;
				}
			}
		});

		//BadgeView badgeView = new BadgeView(this, systemMessgeText);  
		//badgeView.setText("5"); 
		//badgeView.setBadgePosition(BadgeView.POSITION_CENTER);
		//badgeView.show();


		int screenWidth  = getWindowManager().getDefaultDisplay().getWidth();       // 屏幕宽（像素，如：480px）  
		int screenHeight = getWindowManager().getDefaultDisplay().getHeight();

		//创建TipsImageView
		tipsImageView = (TipsImageView)findViewById(R.id.tipsImageView);
		//创建全局属性 ，这里不创建也可以，默认黑色，半透明
		GlobalAttr elseAttr = new GlobalAttr(Color.BLACK);
		//设置全局属性
		tipsImageView.setGlobalAttr(elseAttr);
		//为滑动区域生成tip属性
		TipsAttr slideTipsAttr = new TipsAttr("<---左右滑动--->\n试一试", 50, Color.WHITE);
		Rect rect = new Rect(screenWidth/2,screenHeight/2 , 0, 0);
		//提交属性
		tipsImageView.addArea2View(rect,slideTipsAttr);
		//监听跳过事件
		tipsImageView.setOnSkipActionListener(new OnSkipActionListener() {

			@Override
			public void skipTrigger() {
				// TODO Auto-generated method stub
				Log.v("tipslog", "skipTrigger");
				Toast.makeText(TabActivity.this, "捕获了skip事件", Toast.LENGTH_SHORT).show();
			}
		});
		//监听单击事件
		tipsImageView.setOnTipsClickActionListener(new OnTipsClickActionListener() {

			@Override
			public void clickTrigger() {
				// TODO Auto-generated method stub
				Log.v("tipslog", "clickTrigger");
				Toast.makeText(TabActivity.this, "捕获了点击事件", Toast.LENGTH_SHORT).show();
			}
		});
		//自此创建完成，以下为显示和事件监听
		tipsImageView.showTips();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tab1layout:
			mPager.setCurrentItem(PAGE1);// 点击页面1

			break;
		case R.id.tab2layout:
			mPager.setCurrentItem(PAGE2);// 点击页面1
			break;
		case R.id.tab3layout:
			mPager.setCurrentItem(PAGE3);// 点击页面1
			break;
		case R.id.tab4layout:
			mPager.setCurrentItem(PAGE4);// 点击页面1
			break;
		default:
			break;
		}
	}
	/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//mi.inflate(R.menu.friend_list, menu);
		return super.onCreateOptionsMenu(menu);
	}
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.exitmenu, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		/*
		if (messageDB != null)
			messageDB.close();
		 */
	}

	@Override
	// 菜单选项添加事件处理
	public boolean onOptionsItemSelected(MenuItem item) {
		/*
		switch (item.getItemId()) {
		case R.id.friend_menu_add:
			Toast.makeText(getApplicationContext(), "亲！此功能暂未实现哦", 0).show();
			break;
		case R.id.friend_menu_exit:
			exitDialog(FriendListActivity.this, "QQ提示", "亲！您真的要退出吗？");
			break;
		default:
			break;
		}
		 */
		return super.onOptionsItemSelected(item);
	}

	// 完全退出提示窗
	private void exitDialog(Context context, String title, String msg) {
		/*
		new AlertDialog.Builder(context).setTitle(title).setMessage(msg)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 关闭服务
						if (application.isClientStart()) {
							Intent service = new Intent(
									FriendListActivity.this,
									GetMsgService.class);
							stopService(service);
						}
						close();// 父类关闭方法
					}
				}).setNegativeButton("取消", null).create().show();
		 */
	}
	/*
	@Override
	public void getMessage(TranObject msg) {// 重写父类的方法，处理消息
		// TODO Auto-generated method stub
		switch (msg.getType()) {
		case MESSAGE:
			newNum++;
			application.setRecentNum(newNum);// 保存到全局变量
			TextMessage tm = (TextMessage) msg.getObject();
			String message = tm.getMessage();
			ChatMsgEntity entity = new ChatMsgEntity("", MyDate.getDateEN(),
					message, -1, true);// 收到的消息
			messageDB.saveMsg(msg.getFromUser(), entity);// 保存到数据库
			Toast.makeText(FriendListActivity.this,
					"亲！新消息哦 " + msg.getFromUser() + ":" + message, 0).show();// 提示用户
			MediaPlayer.create(this, R.raw.msg).start();// 声音提示
			User user2 = userDB.selectInfo(msg.getFromUser());// 通过id查询对应数据库该好友信息
			RecentChatEntity entity2 = new RecentChatEntity(msg.getFromUser(),
					user2.getImg(), newNum, user2.getName(), MyDate.getDate(),
					message);
			application.getmRecentAdapter().remove(entity2);// 先移除该对象，目的是添加到首部
			application.getmRecentList().addFirst(entity2);// 再添加到首部
			application.getmRecentAdapter().notifyDataSetChanged();
			break;
		case LOGIN:
			User loginUser = (User) msg.getObject();
			Toast.makeText(FriendListActivity.this,
					"亲！" + loginUser.getId() + "上线了哦", 0).show();
			MediaPlayer.create(this, R.raw.msg).start();
			break;
		case LOGOUT:
			User logoutUser = (User) msg.getObject();
			Toast.makeText(FriendListActivity.this,
					"亲！" + logoutUser.getId() + "下线了哦", 0).show();
			MediaPlayer.create(this, R.raw.msg).start();
			break;
		default:
			break;
		}
	}
	 */
	@Override
	public void onBackPressed() {// 捕获返回按键事件，进入后台运行
		// TODO Auto-generated method stub
		// 发送广播，通知服务，已进入后台运行
		/*
		Intent i = new Intent();
		i.setAction(Constants.BACKKEY_ACTION);
		sendBroadcast(i);

		util.setIsStart(true);// 设置后台运行标志，正在运行
		finish();// 再结束自己
		 */

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_MENU) {
			// 在这里做你想做的事情
			//super.openOptionsMenu();  // 调用这个，就可以弹出菜单
			//实例化SelectPicPopupWindow
			mExitView = new ExitView(TabActivity.this, itemsOnClick);
			//显示窗口
			mExitView.showAtLocation(TabActivity.this.findViewById(R.id.main_lay), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {// 如果两次按键时间间隔大于2000毫秒，则不退出
				showToask("再按一次退出程序");
				mExitTime = System.currentTimeMillis();// 更新mExitTime
			} else {
				EMMSPushManager.destory(this);
				MyApplication.getInstance().exit();

			}
			return true;
		}
		return true; // 最后，一定要做完以后返回 true，或者在弹出菜单后返回true，其他键返回super，让其他键默认
	}
	//为弹出窗口实现监听类
	private OnClickListener  itemsOnClick = new OnClickListener(){

		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.btn_exit:
				EMMSPushManager.destory(TabActivity.this);
				MyApplication.getInstance().exit();
				break;
			default:
				break;
			}
		}
	};
	// ViewPager页面切换监听
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量

		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			Animation animation = null;
			switch (arg0) {
			case PAGE1:// 切换到页卡1
				if (currentIndex == PAGE2) {// 如果之前显示的是页卡2
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currentIndex == PAGE3) {// 如果之前显示的是页卡3
					animation = new TranslateAnimation(one*2,0, 0, 0);
				}else if (currentIndex == PAGE4) {// 如果之前显示的是页卡3
					animation = new TranslateAnimation(one*3,0, 0, 0);
				}
				cursor.setImageResource(R.drawable.topbar_toleft);
				break;
			case PAGE2:// 切换到页卡2
				updateSystemMsgBadge();
				if (systemMsgList.isEmpty()) {
					//showToask("您没有新消息");
				}
				if (currentIndex == PAGE1) {// 如果之前显示的是页卡1
					cursor.setImageResource(R.drawable.topbar_toright);
					animation = new TranslateAnimation(0,one, 0, 0);
				} else if (currentIndex == PAGE3) {// 如果之前显示的是页卡3
					cursor.setImageResource(R.drawable.topbar_toleft);
					animation = new TranslateAnimation(2*one,one, 0, 0);
				}else if (currentIndex == PAGE4) {// 如果之前显示的是页卡3
					cursor.setImageResource(R.drawable.topbar_toleft);
					animation = new TranslateAnimation(3*one, one, 0, 0);
				}
				break;
			case PAGE3:// 切换到页卡3
				if (currentIndex == PAGE1) {// 如果之前显示的是页卡1
					cursor.setImageResource(R.drawable.topbar_toright);
					animation = new TranslateAnimation(0, 2*one, 0, 0);
				} else if (currentIndex == PAGE2) {// 如果之前显示的是页卡2
					cursor.setImageResource(R.drawable.topbar_toright);
					animation = new TranslateAnimation(one, 2*one, 0, 0);
				}else if (currentIndex == PAGE4) {// 如果之前显示的是页卡3
					cursor.setImageResource(R.drawable.topbar_toleft);
					animation = new TranslateAnimation(3*one, 2*one, 0, 0);
				}
				break;
			case PAGE4:// 切换到页卡4
				if (currentIndex == PAGE1) {// 如果之前显示的是页卡1
					animation = new TranslateAnimation(0, 3*one, 0, 0);
				} else if (currentIndex == PAGE2) {// 如果之前显示的是页卡2
					animation = new TranslateAnimation(one, 3*one, 0, 0);
				}else if (currentIndex == PAGE3) {// 如果之前显示的是页卡3
					animation = new TranslateAnimation(2*one, 3*one, 0, 0);
				}
				cursor.setImageResource(R.drawable.topbar_toright);
				break;
			default:
				break;
			}
			currentIndex = arg0;// 动画结束后，改变当前图片位置
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}
	}

	/**
	 * 好友列表下拉刷新监听与实现，异步任务
	 * 
	 * @author way
	 * 
	 */
	public class MyRefreshListener implements RoomOverviewListView.OnRefreshListener {

		@Override
		public void onRefresh() {
			startTimer(30);
			if (new SharePreferenceUtil(TabActivity.this).getisRealtime()) {
				EMMSPushManager.setRefreshRoomsDataRealtime(TabActivity.this,MyApplication.getUserData().getIdIP(),MyApplication.getUserData().getName());
			}else{
				EMMSPushManager.setRefreshRoomsData(TabActivity.this,MyApplication.getUserData().getIdIP(),MyApplication.getUserData().getName());
			}


			/*
			new AsyncTask<Void, Void, Void>() {
				List<User> list;

				protected Void doInBackground(Void... params) {
					EMMSPushManager.setRefreshRoomsData(TabActivity.this,MyApplication.getUserData().getId(),MyApplication.getUserData().getName());
					// 从服务器重新获取好友列表
					if (application.isClientStart()) {
						ClientOutputThread out = application.getClient()
								.getClientOutputThread();
						TranObject o = new TranObject(TranObjectType.REFRESH);
						o.setFromUser(Integer.parseInt(util.getId()));
						out.setMsg(o);
						// 为了及时收到服务器发过来的消息，我这里直接通过监听收消息线程，获取好友列表，就不通过接收广播了
						ClientInputThread in = application.getClient()
								.getClientInputThread();
						in.setMessageListener(new MessageListener() {

							@Override
							public void Message(TranObject msg) {
								// TODO Auto-generated method stub
								if (msg != null
										&& msg.getType() == TranObjectType.REFRESH) {
									list = (List<User>) msg.getObject();
									if (list.size() > 0) {
										// System.out.println("Friend:" + list);
										initListViewData(list);
										myExAdapter.updata(group);
										userDB.updateUser(list);// 保存到数据库
									}
								}
							}
						});
					}
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					//myExAdapter.notifyDataSetChanged();
					mListView_RoomOverview.onRefreshComplete();
					//Toast.makeText(TabActivity.this, "刷新成功", 0).show();
				}

			}.execute();
			 */
		}

	}

	public LinearLayout getImg_friend_list() {
		return img_friend_list;
	}

	public void setImg_friend_list(LinearLayout img_friend_list) {
		this.img_friend_list = img_friend_list;
	}


	public List<SystemMsgEntity> getSystemMsgList() {
		return systemMsgList;
	}

	public void setSystemMsgList(List<SystemMsgEntity> systemMsgList) {
		this.systemMsgList = systemMsgList;
	}

	public void exit(){  
		finish();
		EMMSPushManager.destory(this);
	}  
	public void addSystemMsg(SystemMsgEntity systemMsgEnity){  

		getSystemMsgList().add(systemMsgEnity);
		setSystemMsgList(systemMsgList);
		updateSystemMsgBadge();
		systemMsgViewAdapter.notifyDataSetChanged();

		MessageDB messageDB = new MessageDB(this);
		messageDB.saveMsg(systemMsgEnity);// 保存到数据库 
		messageDB.close();

	} 
	public void removeMsg(int position){  
		int msgId = getSystemMsgList().get(position).getMsgId();
		getSystemMsgList().remove(position);
		setSystemMsgList(systemMsgList);
		updateSystemMsgBadge();
		systemMsgViewAdapter.notifyDataSetChanged();

		MessageDB messageDB = new MessageDB(this);
		messageDB.removeMsg(msgId);// 保存到数据库 
		messageDB.close();  


	} 
	private void updateSystemMsgBadge() {
		int size = getSystemMsgList().size();
		//systemMsgbadgeView.setBackgroundColor(Color.);
		systemMsgbadgeView.setAlpha(0.6f);
		//systemMsgbadgeView.setTextColor(Color.RED);
		systemMsgbadgeView.setTextSize(10);
		systemMsgbadgeView.setText(String.valueOf(size)); 
		systemMsgbadgeView.setBadgePosition(BadgeView.POSITION_CENTER);
		TranslateAnimation anim = new TranslateAnimation(0, 0, -50, 0);
		anim.setInterpolator(new BounceInterpolator());
		anim.setDuration(2000);
		//systemMsgbadgeView.toggle(anim,null);
		systemMsgbadgeView.show(anim);
	}

	public void updataRoomView(RoomViewEntity roomViewEntity){  

		//getSystemMsgList().add(roomViewEntity);
		//setSystemMsgList(systemMsgList);
		//systemMsgViewAdapter.notifyDataSetChanged();
		//getr
		//myExAdapter.notifyDataSetChanged();
		if (roomViewEntity.getState().equals("000001")) {
			//正常
			mListView_RoomOverview.onRefreshComplete();
		}else {
			//异常
			mListView_RoomOverview.onDataException();
		}

		list_data.clear();
		for (int i = 0; i < 9; i++) {
			User u = new User();
			u.setId(roomViewEntity.getRooms());

			u.setImg(roomview_imgs[i]);
			u.setIsOnline(1);

			switch (i) {
			case 0:
				u.setName(String.format(getString(R.string.yeStr),roomViewEntity.getYe()));
				u.setGroup(0);
				break;
			case 1:
				u.setName(String.format(getString(R.string.bjszStr),roomViewEntity.getBjsz()));
				u.setGroup(0);
				break;
			case 2:
				String fmzt ;
				if(roomViewEntity.getFmzt().equals("1"))
				{
					fmzt = "开";
				}else if(roomViewEntity.getFmzt().equals("2"))
				{
					fmzt = "关";
				}else
				{
					fmzt = "过渡";
				}
				u.setName(String.format(getString(R.string.fmztStr),fmzt));
				u.setGroup(0);
				break;
			case 3:
				u.setName(String.format(getString(R.string.zjeStr),roomViewEntity.getZje()));
				u.setGroup(0);
				break;
			case 4:
				u.setName(String.format(getString(R.string.jswdStr),roomViewEntity.getJswd()));
				u.setGroup(0);
				break;
			case 5:
				u.setName(String.format(getString(R.string.hswdStr),roomViewEntity.getHswd()));
				u.setGroup(0);
				break;
			case 6:
				u.setName(String.format(getString(R.string.llStr),roomViewEntity.getLs()));
				u.setGroup(0);
				break;
			case 7:
				u.setName(String.format(getString(R.string.dbyeStr),roomViewEntity.getDbye()));
				u.setGroup(1);
				break;
			case 8:
				u.setName(String.format(getString(R.string.sbylStr),roomViewEntity.getSbyl()));
				u.setGroup(2);
				break;
			default:
				break;
			}
			list_data.add(u);
		}
		addData(list_data);
		myExAdapter.notifyDataSetChanged();
	} 
	@Override
	public void onMessageReceived(ServerMessage arg0) {
		super.onMessageReceived(arg0);


	}
	@Override
	public void onReplyReceived(final ReplyBody reply) {
		super.onReplyReceived(reply);
		if (reply.getType().equals("roomview_response")) {
			timerCancle();

			//Toast.makeText(TabActivity.this, "数据刷新成功", 0).show();
			String roomsString = "";
			if (Integer.parseInt(reply.get("roomnum")) >= 1) {
				roomsString = reply.get("mainroom");
			}else {
				roomsString = reply.get("mainroom")+":"+reply.get("elseroom");
			}
			RoomViewEntity roomViewEntity = new RoomViewEntity(roomsString,reply.get("dev_state"),reply.get("ye"), reply.get("bjsz"), reply.get("fmzt"), reply.get("zje"), reply.get("jswd"), reply.get("hswd"), reply.get("ls"), reply.get("time"),reply.get("dbye"),reply.get("sbyl"));
			updataRoomView(roomViewEntity);
		}else if(reply.getType().equals("realtime_roomview_response")){
			timerCancle();

			//Toast.makeText(TabActivity.this, "数据刷新成功", 0).show();
			String roomsString = "";
			if (Integer.parseInt(reply.get("roomnum")) >= 1) {
				roomsString = reply.get("mainroom");
			}else {
				roomsString = reply.get("mainroom")+":"+reply.get("elseroom");
			}
			RoomViewEntity roomViewEntity = new RoomViewEntity(roomsString,reply.get("dev_state"),reply.get("ye"), reply.get("bjsz"), reply.get("fmzt"), reply.get("zje"), reply.get("jswd"), reply.get("hswd"), reply.get("ls"), reply.get("time"),reply.get("dbye"),reply.get("sbyl"));
			updataRoomView(roomViewEntity);
		}

	}
	@Override
	public void hasMsg(SystemMsgEntity arg0) {
		super.hasMsg(arg0);
		//showToask("你有新消息");
		addSystemMsg(arg0);
	}
	public void startTimer(int secends){

		TimerTask task = new TimerTask(){   
			public void run() {
				timerCancle();
				timerStop();
			}   
		};
		recv_timer = new Timer(true);  
		recv_timer.schedule(task,secends*1000);
	}
	public void timerCancle(){
		recv_timer.cancel();
	}
	public void timerStop(){
		Log.v("whale", "timerStop");
		//Toast.makeText(TabActivity.this, "数据刷新失败", 0).show();

		Message message = new Message();      
		message.what = 0x02;      
		handler.sendEmptyMessage(message.what);
	}
	Handler handler = new Handler(){  
		public void handleMessage(Message msg) {  
			switch (msg.what) {      
			case 0x02: 
				showToask("数据刷新失败");
				mListView_RoomOverview.onRefreshFail();
				//mListView_RoomOverview.setonRefreshListener(refreshListener);
				myExAdapter.notifyDataSetChanged();
				break;      
			}      
			super.handleMessage(msg);  
		}    
	}; 

}

